package com.fy.fyspace.controller;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.fy.fyspace.common.annotation.GlobalInterceptor;
import com.fy.fyspace.common.config.UnsplashConfig;
import com.fy.fyspace.common.result.R;
import com.fy.fyspace.constant.ResultMessageConstant;
import com.fy.fyspace.ex.ConditionException;
import com.fy.fyspace.model.vo.unsplash.UnsplashPhotoListVO;
import com.fy.fyspace.model.vo.unsplash.UnsplashPhotoVO;
import com.fy.fyspace.service.TranslationService;
import com.fy.fyspace.service.UnsplashService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import io.swagger.annotations.ApiResponse;
import io.swagger.annotations.ApiResponses;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

import static com.fy.fyspace.common.result.R.ok;

/**
 * Unsplash图片服务控制器
 * 提供图片搜索、随机获取、查看详情等功能
 */
@Api(tags = "Unsplash图片服务", description = "提供图片搜索、随机获取、查看详情等功能")
@RestController
@RequestMapping("/unsplash")
@Slf4j
public class UnsplashController extends BaseController {

    @Resource
    private UnsplashService unsplashService;

    @Resource
    private UnsplashConfig unsplashConfig;

    @Resource
    private TranslationService translationService;


    /**
     * 搜索图片
     * 根据关键词搜索Unsplash图片,支持分页,返回图片列表及分页信息
     * 图片描述会自动翻译为中文
     *
     * @param query   搜索关键词
     * @param page    页码,从1开始
     * @param perPage 每页数量,不传则使用默认值
     * @return 图片列表及分页信息
     */
    @ApiOperation(value = "搜索图片", notes = "根据关键词搜索Unsplash图片,支持分页,返回图片列表及分页信息")
    @ApiResponses({
            @ApiResponse(code = 200, message = "搜索成功"),
            @ApiResponse(code = 500, message = "搜索失败")
    })
    @GetMapping("/search")
    @GlobalInterceptor(checkAdmin = true)
    public R<UnsplashPhotoListVO> searchPhotos(
            @ApiParam(value = "搜索关键词", required = true, example = "nature") @RequestParam String query,
            @ApiParam(value = "页码,从1开始", example = "1") @RequestParam(defaultValue = "1") int page,
            @ApiParam(value = "每页数量,不传则使用默认值", example = "20") @RequestParam(required = false) Integer perPage) {
        try {
            if (perPage == null) {
                perPage = unsplashConfig.getDefaultPerPage();
            }
            if (perPage > unsplashConfig.getMaxPerPage()) {
                perPage = unsplashConfig.getMaxPerPage();
            }

            // 获取搜索结果
            JSONObject result = unsplashService.searchPhotos(query, page, perPage);

            // 创建返回对象
            UnsplashPhotoListVO listVO = new UnsplashPhotoListVO();
            listVO.setTotal(result.getInteger("total"));
            listVO.setTotalPages(result.getInteger("total_pages"));
            listVO.setCurrentPage(page);

            // 处理图片列表
            JSONArray results = result.getJSONArray("results");
            List<UnsplashPhotoListVO.UnsplashPhotoItemVO> photoList = new ArrayList<>();

            for (int i = 0; i < results.size(); i++) {
                JSONObject photo = results.getJSONObject(i);
                UnsplashPhotoListVO.UnsplashPhotoItemVO photoItem = new UnsplashPhotoListVO.UnsplashPhotoItemVO();

                // 设置基本信息
                photoItem.setId(photo.getString("id"));
                photoItem.setLikes(photo.getInteger("likes"));

                // 设置URL
                JSONObject urls = photo.getJSONObject("urls");
                photoItem.setUrl(urls.getString("regular"));

                // 设置作者
                JSONObject user = photo.getJSONObject("user");
                photoItem.setAuthorName(user.getString("name"));

                // 翻译描述
                String description = photo.getString("description");
                if (description != null && !description.isEmpty()) {
                    photoItem.setDescription(translationService.translateToZh(description));
                }

                photoList.add(photoItem);
            }

            listVO.setPhotos(photoList);
            return ok(listVO);
        } catch (Exception e) {
            log.error("搜索图片失败", e);
            throw new ConditionException(ResultMessageConstant.SEARCH_ERROR);
        }
    }

    /**
     * 获取随机图片
     * 随机获取指定数量的Unsplash图片
     * 图片描述会自动翻译为中文
     *
     * @param count 需要获取的图片数量
     * @return 随机图片列表
     */
    @ApiOperation(value = "获取随机图片", notes = "随机获取指定数量的Unsplash图片,描述会自动翻译为中文")
    @ApiResponses({
            @ApiResponse(code = 200, message = "获取成功"),
            @ApiResponse(code = 500, message = "获取失败")
    })
    @GetMapping("/random")
    @GlobalInterceptor(checkAdmin = true)
    public R<List<UnsplashPhotoListVO.UnsplashPhotoItemVO>> getRandomPhotos(
            @ApiParam(value = "图片数量", example = "30") @RequestParam(defaultValue = "30") int count) {
        try {
            if (count > unsplashConfig.getMaxPerPage()) {
                count = unsplashConfig.getMaxPerPage();
            }

            // 获取随机图片
            JSONArray photos = unsplashService.getRandomPhotos(count);
            List<UnsplashPhotoListVO.UnsplashPhotoItemVO> photoList = new ArrayList<>();

            for (int i = 0; i < photos.size(); i++) {
                JSONObject photo = photos.getJSONObject(i);
                UnsplashPhotoListVO.UnsplashPhotoItemVO photoItem = new UnsplashPhotoListVO.UnsplashPhotoItemVO();

                // 设置基本信息
                photoItem.setId(photo.getString("id"));
                photoItem.setLikes(photo.getInteger("likes"));

                // 设置URL
                JSONObject urls = photo.getJSONObject("urls");
                photoItem.setUrl(urls.getString("regular"));

                // 设置作者
                JSONObject user = photo.getJSONObject("user");
                photoItem.setAuthorName(user.getString("name"));

                // 翻译描述
                String description = photo.getString("description");
                if (description != null && !description.isEmpty()) {
                    photoItem.setDescription(translationService.translateToZh(description));
                }

                photoList.add(photoItem);
            }

            return ok(photoList);
        } catch (Exception e) {
            log.error("获取随机图片失败", e);
            throw new ConditionException(ResultMessageConstant.SEARCH_ERROR);
        }
    }

    /**
     * 获取图片详情
     * 根据图片ID获取详细信息,包括作者、标签、下载量等
     * 描述和标签会自动翻译为中文
     *
     * @param photoId 图片ID
     * @return 图片详细信息
     */
    @ApiOperation(value = "获取图片详情", notes = "根据图片ID获取详细信息,包括作者、标签、下载量等,描述和标签会自动翻译为中文")
    @ApiResponses({
            @ApiResponse(code = 200, message = "获取成功"),
            @ApiResponse(code = 500, message = "获取失败")
    })
    @GetMapping("/photos/{id}")
    @GlobalInterceptor(checkAdmin = true)
    public R<UnsplashPhotoVO> getPhotoDetails(
            @ApiParam(value = "图片ID", required = true, example = "xyz123") @PathVariable("id") String photoId) {
        try {
            // 获取原始图片信息
            JSONObject originalPhoto = unsplashService.getPhotoDetails(photoId);

            // 创建VO对象
            UnsplashPhotoVO photoVO = new UnsplashPhotoVO();

            // 设置基本信息
            photoVO.setId(originalPhoto.getString("id"));
            photoVO.setLikes(originalPhoto.getInteger("likes"));

            // 设置URL
            JSONObject urls = originalPhoto.getJSONObject("urls");
            photoVO.setUrl(urls.getString("regular"));

            // 设置作者信息
            JSONObject user = originalPhoto.getJSONObject("user");
            photoVO.setAuthorName(user.getString("name"));
            photoVO.setAuthorUrl(user.getString("portfolio_url"));

            // 设置创建时间
            photoVO.setCreateTime(originalPhoto.getString("created_at"));

            // 设置下载量
            JSONObject statistics = originalPhoto.getJSONObject("statistics");
            if (statistics != null) {
                photoVO.setDownloads(statistics.getJSONObject("downloads").getInteger("total"));
            }

            // 翻译描述
            String description = originalPhoto.getString("description");
            if (description != null && !description.isEmpty()) {
                String translatedDescription = translationService.translateToZh(description);
                photoVO.setDescription(translatedDescription);
            }

            // 翻译并设置标签
            if (originalPhoto.containsKey("tags")) {
                JSONArray tags = originalPhoto.getJSONArray("tags");
                List<String> tagTitles = new ArrayList<>();
                for (int i = 0; i < tags.size(); i++) {
                    JSONObject tag = tags.getJSONObject(i);
                    tagTitles.add(tag.getString("title"));
                }

                // 翻译标签
                String[] translatedTags = translationService.translateToZhBatch(
                        tagTitles.toArray(new String[0]));

                photoVO.setTags(Arrays.asList(translatedTags));
            }

            return ok(photoVO);
        } catch (Exception e) {
            log.error("获取图片详情失败", e);
            throw new ConditionException(ResultMessageConstant.SEARCH_ERROR);
        }
    }

    /**
     * 获取热门图片
     * 获取Unsplash上的热门图片,支持分页
     * 图片描述会自动翻译为中文
     *
     * @param page    页码,从1开始
     * @param perPage 每页数量,不传则使用默认值
     * @return 热门图片列表
     */
    @ApiOperation(value = "获取热门图片", notes = "获取Unsplash上的热门图片,支持分页,描述会自动翻译为中文")
    @ApiResponses({
            @ApiResponse(code = 200, message = "获取成功"),
            @ApiResponse(code = 500, message = "获取失败")
    })
    @GetMapping("/photos/popular")
    @GlobalInterceptor(checkAdmin = true)
    public R<List<UnsplashPhotoListVO.UnsplashPhotoItemVO>> getPopularPhotos(
            @ApiParam(value = "页码,从1开始", example = "1") @RequestParam(defaultValue = "1") int page,
            @ApiParam(value = "每页数量,不传则使用默认值", example = "20") @RequestParam(required = false) Integer perPage) {
        try {
            if (perPage == null) {
                perPage = unsplashConfig.getDefaultPerPage();
            }
            if (perPage > unsplashConfig.getMaxPerPage()) {
                perPage = unsplashConfig.getMaxPerPage();
            }

            // 获取热门图片
            JSONArray photos = unsplashService.getPopularPhotos(page, perPage);
            List<UnsplashPhotoListVO.UnsplashPhotoItemVO> photoList = new ArrayList<>();

            for (int i = 0; i < photos.size(); i++) {
                JSONObject photo = photos.getJSONObject(i);
                UnsplashPhotoListVO.UnsplashPhotoItemVO photoItem = new UnsplashPhotoListVO.UnsplashPhotoItemVO();

                // 设置基本信息
                photoItem.setId(photo.getString("id"));
                photoItem.setLikes(photo.getInteger("likes"));

                // 设置URL
                JSONObject urls = photo.getJSONObject("urls");
                photoItem.setUrl(urls.getString("regular"));

                // 设置作者
                JSONObject user = photo.getJSONObject("user");
                photoItem.setAuthorName(user.getString("name"));

                // 翻译描述
                String description = photo.getString("description");
                if (description != null && !description.isEmpty()) {
                    photoItem.setDescription(translationService.translateToZh(description));
                }

                photoList.add(photoItem);
            }

            return ok(photoList);
        } catch (Exception e) {
            log.error("获取热门图片失败", e);
            throw new ConditionException(ResultMessageConstant.SEARCH_ERROR);
        }
    }
}